//
//  StockAppService.m
//  Stock
//
//  Created by blacksun on 11-6-30.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "StockAppService.h"
#import "UIDevice+IdentifierAddition.h"
#import "StockRadar.h"

@implementation StockAppService 


-(void)signUp{
    UIDevice *device = [UIDevice currentDevice];
    NSString *signUpUrl = [[NSString alloc] initWithFormat:@"%@srv/iphone/user/register?d=%@&os=%@&sv=%@",kHostName,[device myDeviceIdentifier],device.systemVersion,AppVersionCode];
    NSLog(@"%@",signUpUrl);
    NSURL *url = [[NSURL alloc] initWithString:signUpUrl];
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
    request.delegate = self;
    request.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:kStockAppServiceSignUp,kASIHttpRequestUserinfoKey, nil];
    [request startAsynchronous];
    [self.workingRequests addObject:request];
    [request release];
    [url release];
    [signUpUrl release];
}
-(void)logout{

    NSString *loginString = [[NSString alloc] initWithFormat:@"%@user/logout?u=%@&sv=%@",kHostName,    [StockContext shareInstance].userId,AppVersionCode];
    NSURL *url = [[NSURL alloc] initWithString:loginString];
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
    request.delegate = self;
    request.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:kStockAppServiceLogout,kASIHttpRequestUserinfoKey,nil];
    [request startAsynchronous];
    [self.workingRequests addObject:request];
    [request release];
    [url release];
    [loginString release];
}
-(void)loginWithUserId:(NSString *)userId{
    NSString *loginString = [[NSString alloc] initWithFormat:@"%@srv/iphone/user/login?u=%@&os=%@&sv=%@",kHostName,userId,[UIDevice currentDevice].systemVersion,AppVersionCode];
    NSLog(@"%@",loginString);
    NSURL *url = [[NSURL alloc] initWithString:loginString];
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
    request.delegate = self;
    request.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:kStockAppServiceLogin,kASIHttpRequestUserinfoKey,nil];
    [request startAsynchronous];
    [self.workingRequests addObject:request];
    [request release];
    [url release];
    [loginString release];
}
-(void)sendPushToken:(NSString *)token{
    NSString *loginString = [[NSString alloc] initWithFormat:@"%@srv/iphone/user/token?t=%@&u=%@",kHostName,token,[StockContext shareInstance].userId];
    NSURL *url = [[NSURL alloc] initWithString:loginString];
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
    request.delegate = self;
    [request startAsynchronous];
    [self.workingRequests addObject:request];
    [request release];
    [url release];
    [loginString release];
}


#pragma mark -delegate callback
- (void)requestFinished:(ASIHTTPRequest *)request{
    NSDictionary *userinfo = request.userInfo;
    CommonUtil *commonUtil = [CommonUtil shareInstance];
    NSString *action = [userinfo objectForKey:kASIHttpRequestUserinfoKey];
    //NSLog(@"action:%@",action);
    if ([kStockAppServiceLogin isEqualToString:action]) {
        NSString *responseString = [request responseString];
        NSDictionary *json = [responseString JSONValue];
        [StockContext shareInstance].updateTimes = [json objectForKey:@"functions"];
        [StockContext shareInstance].radarDays = [[json objectForKey:@"radarDays"] intValue];
        [StockContext shareInstance].radarTest = [[json objectForKey:@"radarTest"] boolValue];
        [StockContext shareInstance].paid = [[json objectForKey:@"paid"] boolValue];
        NSString *date = [json objectForKey:@"radarExpiryDate"];
        [[StockContext shareInstance] updateaRadarDate:date];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:kNeedUpdateRadarDateNotification object:nil];
        
        NSArray *sections = [json objectForKey:@"sections"];
        if (!sections || [sections count]==0) {
            [self.delegate requestFinishedWithResult:nil andUserinfo:request.userInfo];
            return;
        }
        NSMutableArray *newSections = [NSMutableArray array];
        for (NSDictionary *dict in sections) {
            Section *section = [[Section alloc] init];
            [commonUtil copyMapEntries:dict toObject:section];
            [newSections addObject:section];
            [section release];
        }
        [self.delegate requestFinishedWithResult:newSections andUserinfo:userinfo];
        NSArray *oldSections = [Section allObjects];
        [oldSections makeObjectsPerformSelector:@selector(deleteObject)];
        [super batchAndAsynchronousSaveObjects:newSections];
        
    }else if([kStockAppServiceSignUp isEqualToString:action]){
        NSDictionary *responseDict = [[request responseString] JSONValue];
        if (!responseDict || [responseDict count]==0) {
            [self.delegate requestFinishedwithError:nil andUserinfo:request.userInfo];
            return;
        }
        NSString *userId = [responseDict objectForKey:@"userId"];
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
        [userDefault setObject:userId forKey:kUserIdInUserDefault];
        [userDefault synchronize];
        //NSLog(@"userid=%@",userId);
        [StockContext shareInstance].userId = userId;
        
        [StockContext shareInstance].radarDays = [[responseDict objectForKey:@"radarDays"] intValue];
        [StockContext shareInstance].radarTest = [[responseDict objectForKey:@"radarTest"] boolValue];
        [StockContext shareInstance].paid = [[responseDict objectForKey:@"paid"] boolValue];
        NSString *date = [responseDict objectForKey:@"radarExpiryDate"];
        [[StockContext shareInstance] updateaRadarDate:date];
        NSString *email = [responseDict objectForKey:@"email"];
        if (email.length>0) {
            [[StockContext shareInstance] saveChargeEmail:email];
        }
        
        [[NSNotificationCenter defaultCenter] postNotificationName:kNeedUpdateRadarDateNotification object:nil];
        
        NSArray *sections = [responseDict objectForKey:@"sections"];
        NSMutableArray *newSections = [NSMutableArray array];
        for (NSDictionary *dict in sections) {
            Section *section = [[Section alloc] init];
            [commonUtil copyMapEntries:dict toObject:section];
            [newSections addObject:section];
            [section release];
        }
        NSArray *oldSections = [Section allObjects];
        [oldSections makeObjectsPerformSelector:@selector(deleteObject)];
        [super batchAndAsynchronousSaveObjects:newSections];
        
        NSArray *stocks = [responseDict objectForKey:@"stocks"];
        NSMutableArray *myStocks = [[NSMutableArray alloc] init];
        for (NSDictionary *dict in stocks) {
            MyStock *myStock = [[MyStock alloc] init];
            [commonUtil copyMapEntries:dict toObject:myStock];
            [myStocks addObject:myStock];
            [myStock release];
        }
        NSArray *radars = [responseDict objectForKey:@"monitors"];
        if (radars && radars.count>0) {
            for (NSDictionary *dict in radars) {
                StockRadar *radar = [[StockRadar alloc] init];
                radar.id = [dict objectForKey:@"uuid"];
                radar.stockId = [dict objectForKey:@"stockId"];
                radar.type = [[dict objectForKey:@"direction"] intValue];
                radar.targetValue = [NSString stringWithFormat:@"%0.2f",[[dict objectForKey:@"threshold"] floatValue]];
                [radar save];
                [radar release];
            }
        }
        [super batchAndAsynchronousSaveObjects:myStocks];
        [myStocks release];
        
        NSString *radarStatus = [responseDict objectForKey:@"radarStatus"];
        if (radarStatus.length>0) {
            NSMutableDictionary *values = [NSMutableDictionary dictionary];
            for (int i=0; i<radarStatus.length; i++) {
                NSString *str = [radarStatus substringWithRange:NSRangeFromString([NSString stringWithFormat:@"%d,1",i])];
                NSNumber *number = [NSNumber numberWithBool:[str boolValue]];
                [values setValue:number forKey:[NSString stringWithFormat:@"%d",i+1]];
            }
            [values writeToFile:kRadarSettingFile atomically:YES];
        }
        NSString *radarRange = [responseDict objectForKey:@"radarRange"];
        if (radarRange.length>0) {
            NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
            [userDefault setInteger:[radarRange intValue] forKey:RadarRangeKey];
            [userDefault synchronize];
        }
        
        [self.delegate requestFinishedWithResult:newSections andUserinfo:userinfo];
    }else if([action isEqualToString:kStockAppServiceNewOpinion]){
        NSString *responseString = [request responseString];
        NSDictionary *json = [responseString JSONValue];
        [self.delegate requestFinishedWithResult:[json objectForKey:@"stocks"] andUserinfo:request.userInfo];
    }else if([action isEqualToString:kStockAppServiceQueryOpinionPool]){
        NSString *responseString = [request responseString];
        NSDictionary *json = [responseString JSONValue];
        [self.delegate requestFinishedWithResult:[json objectForKey:@"stocks"] andUserinfo:request.userInfo];
    }else if([action isEqualToString:kStockAppServiceModifySystemRadar]){
        [self.delegate requestFinishedWithResult:nil andUserinfo:request.userInfo];
    }else if([action isEqualToString:kSubmitAnswers]){
        [self.delegate requestFinishedWithResult:nil andUserinfo:request.userInfo];
    }else if ([action isEqualToString:kStockAppServiceModifyRadarRange]) {
        [self.delegate requestFinishedWithResult:[request.responseString JSONValue] andUserinfo:request.userInfo];
    }
}
-(void)queryOpinionPool{
    NSString *loginString = [[NSString alloc] initWithFormat:@"%@jf/bh/pool.jf",kHostName];
    NSLog(@"%@",loginString);
    NSURL *url = [[NSURL alloc] initWithString:loginString];
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
    request.delegate = self;
    request.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:kStockAppServiceQueryOpinionPool,kASIHttpRequestUserinfoKey,nil];
    [request startAsynchronous];
    [self.workingRequests addObject:request];
    [request release];
    [url release];
    [loginString release];

}

-(void)queryNewOpinionWithIndex:(NSInteger )index andType:(NSString *)type{
    NSString *loginString = nil;
    if ([type isEqualToString:@"weekgrowth"]) {
        loginString = [[NSString alloc] initWithFormat:@"%@/jf/opinion/growth/%d.jf",kHostName,index*20];
    }else{
        loginString = [[NSString alloc] initWithFormat:@"%@jf/bh/trace/%d.jf",kHostName,index*20];
    }
    NSLog(@"%@",loginString);
    NSURL *url = [[NSURL alloc] initWithString:loginString];
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
    request.delegate = self;
    request.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:kStockAppServiceNewOpinion,kASIHttpRequestUserinfoKey,nil];
    [request startAsynchronous];
    [self.workingRequests addObject:request];
    [request release];
    [url release];
    [loginString release];
    
}
-(void)modifySystemRadar:(NSString *)radarId state:(BOOL)state{
    NSString *radarState = [NSString stringWithFormat:@"%d",[[NSNumber numberWithBool:state] intValue]];
    NSString *loginString = [[NSString alloc] initWithFormat:@"%@srv/iphone/radar/status?u=%@&r=%@&s=%@",kHostName,[StockContext shareInstance].userId,radarId,radarState];
    NSLog(@"%@",loginString);
    NSURL *url = [[NSURL alloc] initWithString:loginString];
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
    request.delegate = self;
    NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:kStockAppServiceModifySystemRadar,kASIHttpRequestUserinfoKey,radarId,@"radarId",radarState,@"radarState",nil];
    request.userInfo = userInfo;
    [request startAsynchronous];
    [self.workingRequests addObject:request];
    [request release];
    [url release];
    [loginString release];
}
-(void)modifyRadarRange:(NSInteger)range{
    NSString *loginString = [[NSString alloc] initWithFormat:@"%@srv/iphone/radar/range?u=%@&r=%d",kHostName,[StockContext shareInstance].userId,range];
    NSLog(@"%@",loginString);
    NSURL *url = [[NSURL alloc] initWithString:loginString];
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
    request.delegate = self;
    NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:kStockAppServiceModifyRadarRange,kASIHttpRequestUserinfoKey,[NSString stringWithFormat:@"%d",range],@"range",nil];
    request.userInfo = userInfo;
    [request startAsynchronous];
    [self.workingRequests addObject:request];
    [request release];
    [url release];
    [loginString release];
}

-(void)submitAnswers:(NSString *)answer{
    NSURL *url = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"%@/srv/iphone/question/answer?u=%@&a=%@",kHostName,[StockContext shareInstance].userId,answer]];
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
    request.delegate = self;
    request.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:kSubmitAnswers,kASIHttpRequestUserinfoKey,nil];
    [request startAsynchronous];
    [self.workingRequests addObject:request];
    [request release];
    [url release];
}

- (void)requestFailed:(ASIHTTPRequest *)request{
    NSError *error = request.error;
    NSLog(@"code=%d,%@",[error code],error);
    [self.delegate requestFinishedwithError:request.error andUserinfo:request.userInfo];
}

@end
